#include "SysPoll.h"

SYS_POLL_T g_sys_poll[SYS_POLL_NUM];
static uint32_t g_pollNum = 0;

#define HAS_PAST_POLL(oldPollNum, delay)  ((g_pollNum-oldPollNum)>delay)
#define UPDATE_POLL_NUM()  g_pollNum

void sysPeriodInit(void)
{
    memset(g_sys_poll, 0, sizeof(g_sys_poll));
}

SYS_POLL_T *sysPeriodPollSet(uint16_t round, POLL_TIMES_T time, POLL_HANDLE_T handle, void *args, uint8_t delay)
{
    uint8_t i;
    SYS_POLL_T *period = NULL;
    for(i = 0; i < SYS_POLL_NUM; i++)
    {
        if(!g_sys_poll[i].alloced)
        {
            period = &g_sys_poll[i];
            break;
        }
    }
    if(period == NULL)
    {
        return NULL;
    }

    period->alloced  = true;
    period->posNow   = 0;
    period->roundNum = round;
    period->times    = time;
    period->pollHandle = handle;
    period->args     = args;
    period->delay    = delay;
    //period->now      = UPDATE_POLL_NUM();
    period->now      = SysTime();

    return period;
}

void sysPeriodPoll(void)
{
    uint8_t i;
    SYS_POLL_T *period;

    for(i = 0; i < SYS_POLL_NUM; i++)
    {
        period = &g_sys_poll[i];
        if(period->alloced)
        {
            if(period->posNow < period->roundNum)
            {
                //if(HAS_PAST_POLL(period->now, period->delay))
                if(SysTimeHasPast(period->now, period->delay))
                {
                    if(period->pollHandle(period->posNow, period->args) == 0)
                    {
                        period->now = SysTime();
                    }
                    period->posNow++;
                    //period->now = UPDATE_POLL_NUM();
                }
            }
            else
            {
                if(period->times == POLL_ONCE)
                {
                    period->alloced = false;
                }
                period->posNow  = 0;
            }
        }
    }
    g_pollNum++;
}

void sysPeriodPollClear(SYS_POLL_T *period)
{
    period->alloced = false;
    period->posNow  = 0;
}

